import { areaData } from "../config/index";

const addressParse = (provinceName, cityName, countryName) => {
  const province = areaData.find((v) => v.label === provinceName);
  const { value: provinceCode } = province;
  const city = province.children.find((v) => v.label === cityName);
  const { value: cityCode } = city;
  const country = city.children.find((v) => v.label === countryName);
  const { value: districtCode } = country;
  return {
    provinceCode,
    cityCode,
    districtCode,
  };
};

/**
 * 拆分地址函数
 * @param {string} address - 完整的地址字符串
 * @returns {Object} 包含省、市、区和详细地址的对象
 */
function splitAddress(address) {
  // 正则表达式，用于匹配省、市、自治区、县、区等关键词
  const reg = /.+?(省|市|自治区|自治州|县|区)/g;
  const list = address.match(reg) || []; // 防止匹配不到时出现null

  let province = "",
    city = "",
    area = "";

  // 根据匹配到的部分数量进行分配，以应对不同格式的地址
  if (list.length === 2) {
    // 处理类似"北京市海淀区"这样的直辖市地址
    city = list[0];
    area = list[1];
  } else if (list.length >= 3) {
    // 处理标准格式"省-市-区"
    province = list[0];
    city = list[1];
    area = list[2];
  }

  // 剩余部分为详细地址
  const detail = address.substring(province.length + city.length + area.length);

  return {
    province: province,
    city: city,
    district: area,
    detail: detail.trim(), // 去除首尾空格
  };
}

module.exports = {
  addressParse,
  splitAddress,
};
